let blogInfoModel = require("../../model/blog/blogTable");
let Service = {
  add: (info) => blogInfoModel.insertMany([info]),
  query: (info) => {
    const { sortNoTop, tags, ...otherInfo } = info;
    // 构建查询条件
    const queryConditions = { ...otherInfo };
    // 添加标签查询条件
    if (tags && tags.length > 0) {
      queryConditions.tag = { $in: tags };
    }
    // 构建排序条件
    const sortCondition = sortNoTop ? { createTime: -1 } : { top: -1, createTime: -1 };
    // 执行查询
    return blogInfoModel.find(queryConditions).sort(sortCondition);
  },
  delete: (info) => blogInfoModel.remove(info),
  update: (info) => blogInfoModel.updateOne({ _id: info._id }, info),
  //设置redNum
  updateRedNum: ({ _id, readNum }) => blogInfoModel.updateOne({ _id }, { $set: { readNum } }),
  //获取博客类型+数量
  getBlogTypeNum: () => blogInfoModel.aggregate([
    {
      $group: {
        _id: '$type',
        count: { $sum: 1 }
      }
    },
    {
      $project: {
        type: '$_id',
        count: 1,
        _id: 0
      }
    }
  ]),
  //获取标签类型+数量
  getBlogTagNum: () => blogInfoModel.aggregate([
    {
      $unwind: "$tag" // 将标签数组拆分为多个文档
    },
    {
      $group: {
        _id: "$tag", // 按照标签分组
        count: { $sum: 1 } // 统计每个标签的文章数量
      }
    },
    {
      $project: {
        tag: '$_id',
        count: 1,
        _id: 0
      }
    },
    {
      $sort: { count: -1 } // 按文章数量降序排序
    }
  ])
};
module.exports = Service;
